package com.neusoft.mabaitspius.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UplodeController {

    @RequestMapping("/upload")
    public String upload(MultipartFile myFile) throws IOException {
        //上传文件的路径
        String path ="E:/upload";
        //获取上传的文件名
        String fileName = myFile.getOriginalFilename();
        String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        File file = new File(path,newFileName);
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            myFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }

    @PostMapping("/uploadMany")
    public String uploadMany(
            // 参数名 "myFiles" 必须与前端 fd.append 的键名一致
            @RequestParam("myFiles") MultipartFile myFile
    ) {
        // 1. 校验文件非空
        if (myFile.isEmpty()) {
            return "文件为空";
        }
        String path ="E:/upload";
        try {
            // 2. 处理文件（示例：保存到本地）
            String fileName = myFile.getOriginalFilename();
            String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
            File targetFile = new File(path , newFileName);
            // 确保父目录存在
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            myFile.transferTo(targetFile);
            return "ok"; // 与前端判断逻辑匹配
        } catch (IOException e) {
            e.printStackTrace();
            return "文件处理失败: " + e.getMessage();
        }
    }
}
